package org.itboys.core.service.mysql.web;

import org.apache.commons.collections.map.HashedMap;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.core.common.SundayCommonConstants;
import org.itboys.core.dao.order.SundayOutStoreOrderMapper;
import org.itboys.core.dao.order.SundayOutStoreOrderSKUMapper;
import org.itboys.core.entity.mysql.*;
import org.itboys.core.util.NumberUtil;
import org.itboys.mysql.service.BaseMySqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author：贾琦磊
 * @Date：2018/8/24
 * @Description：出库单service
 */
@Service
public class SundayOutStoreOrderService extends BaseMySqlService<SundayOutStoreOrder>{
    private static final String PREFIX="OutStoreOrder";
    @Autowired
    private SundayOutStoreOrderMapper outStoreOrderMapper;
    @Autowired
    private SundayOutStoreOrderSKUMapper outStoreOrderSKUMapper;
    @Autowired
    private SundayStoreAddService storeAddService;

    /**
     * 根据退货单生成出库单,必须生成库存增量
     * @param reProductOrder
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(SundayReProductOrder reProductOrder,List<SundayReProductOrderSKU> skus){
        Map<String,Object> param=new HashedMap();
        SundayOutStoreOrder outStoreOrder=new SundayOutStoreOrder();
        outStoreOrder.setNumber(NumberUtil.generateNumber(PREFIX));
        outStoreOrder.setOrderId(reProductOrder.getId());
        outStoreOrder.setPreStoreId(reProductOrder.getPreStoreId());
        outStoreOrder.setReason(SundayOutStoreOrder.REASON_OUT);
        outStoreOrder.setType(SundayCommonConstants.ORDER_TYPE_RE_PRODUCT);
        outStoreOrderMapper.insert(outStoreOrder);
        List<SundayOutStoreOrderSKU> _skus=new ArrayList<>();
        List<SundayStoreAdd> storeAdds=new ArrayList<>();
        //生成库存增量和出库单sku附表
        for (SundayReProductOrderSKU sku:skus
             ) {
            SundayOutStoreOrderSKU _sku=new SundayOutStoreOrderSKU();
            SundayStoreAdd storeAdd=new SundayStoreAdd();
            storeAdd.setOrderNumber(outStoreOrder.getNumber());
            storeAdd.setSKUId(sku.getSKUId());
            storeAdd.setNum(-sku.getNum());
            storeAdd.setOrderId(outStoreOrder.getId());
            storeAdd.setOrderType(SundayCommonConstants.ORDER_TYPE_OUT_STORE);
            storeAdd.setStoreId(outStoreOrder.getPreStoreId());
            _sku.setOrderId(outStoreOrder.getId());
            _sku.setNum(sku.getNum());
            _sku.setSKUId(sku.getSKUId());
            _skus.add(_sku);
            storeAdds.add(storeAdd);
        }
        if(ListUtil.isNotNull(_skus)){
            outStoreOrderSKUMapper.insertSKUs(_skus);
        }
        if(ListUtil.isNotNull(storeAdds)){
            storeAddService.insert(storeAdds);
        }
    }
}
